#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "cJSON.h"
#include "common.h"
#include "user.h"

// 日志函数声明（需要从外部引入）
void logDebug(const char *format, ...);
void logInfo(const char *format, ...);
void logError(const char *format, ...);
void logFatal(const char *format, ...);

// 外部变量声明
extern pthread_mutex_t responseMutex;
extern pthread_cond_t responseCond;
extern char g_responseBuffer[MAX_BUFFER_SIZE];
extern unsigned char g_responseDataType;
extern int g_responseReady;

// 等待并获取服务器响应（从client.c迁移）
int waitForResponse(char *buffer, int bufferSize, unsigned char *dataType) {
    pthread_mutex_lock(&responseMutex);
    
    // 等待响应
    while (!g_responseReady) {
        pthread_cond_wait(&responseCond, &responseMutex);
    }
    
    // 复制响应数据
    strncpy(buffer, g_responseBuffer, bufferSize - 1);
    *dataType = g_responseDataType;
    g_responseReady = 0;
    
    pthread_mutex_unlock(&responseMutex);
    return strlen(buffer);
}

// 用户登录
int userLogin(ClientContext *context, const char *username, const char *password) {
    cJSON *root = cJSON_CreateObject();
    cJSON_AddStringToObject(root, "username", username);
    cJSON_AddStringToObject(root, "password", password);
    
    char *jsonStr = cJSON_PrintUnformatted(root);
    int ret = sendPacket(context->sockfd, DATA_TYPE_USER_LOGIN, jsonStr);
    
    cJSON_free(jsonStr);
    cJSON_Delete(root);
    
    if (ret < 0) {
        logError("Failed to send login request");
        return -1;
    }
    
    // 等待响应
    char responseBuffer[MAX_BUFFER_SIZE];
    unsigned char responseType;
    waitForResponse(responseBuffer, MAX_BUFFER_SIZE, &responseType);
    
    cJSON *response = cJSON_Parse(responseBuffer);
    if (response) {
        if (responseType == DATA_TYPE_ACK) {
            cJSON *role = cJSON_GetObjectItem(response, "role");
            if (role) {
                strncpy(context->user.username, username, sizeof(context->user.username) - 1);
                strncpy(context->user.password, password, sizeof(context->user.password) - 1);
                strncpy(context->user.role, role->valuestring, sizeof(context->user.role) - 1);
                context->loggedIn = 1;
                logInfo("Login successful, user role: %s", role->valuestring);
                cJSON_Delete(response);
                return 0;
            }
        }
        cJSON_Delete(response);
    }
    
    logError("Login failed");
    return -1;
}

// 用户注册
int userRegister(ClientContext *context, const char *username, const char *password, const char *role) {
    cJSON *root = cJSON_CreateObject();
    cJSON_AddStringToObject(root, "username", username);
    cJSON_AddStringToObject(root, "password", password);
    cJSON_AddStringToObject(root, "role", role);
    
    char *jsonStr = cJSON_PrintUnformatted(root);
    int ret = sendPacket(context->sockfd, DATA_TYPE_USER_REGISTER, jsonStr);
    
    cJSON_free(jsonStr);
    cJSON_Delete(root);
    
    if (ret < 0) {
        logError("Failed to send register request");
        return -1;
    }
    
    // 等待响应
    char responseBuffer[MAX_BUFFER_SIZE];
    unsigned char responseType;
    waitForResponse(responseBuffer, MAX_BUFFER_SIZE, &responseType);
    
    if (responseType == DATA_TYPE_ACK) {
        logInfo("Register successful");
        return 0;
    }
    
    logError("Register failed");
    return -1;
}

// 修改密码
int userChangePassword(ClientContext *context, const char *oldPassword, const char *newPassword) {
    cJSON *root = cJSON_CreateObject();
    cJSON_AddStringToObject(root, "username", context->user.username);
    cJSON_AddStringToObject(root, "oldPassword", oldPassword);
    cJSON_AddStringToObject(root, "newPassword", newPassword);
    
    char *jsonStr = cJSON_PrintUnformatted(root);
    int ret = sendPacket(context->sockfd, DATA_TYPE_USER_CHANGE_PASSWORD, jsonStr);
    
    cJSON_free(jsonStr);
    cJSON_Delete(root);
    
    if (ret < 0) {
        logError("Failed to send change password request");
        return -1;
    }
    
    // 等待响应
    char responseBuffer[MAX_BUFFER_SIZE];
    unsigned char responseType;
    waitForResponse(responseBuffer, MAX_BUFFER_SIZE, &responseType);
    
    if (responseType == DATA_TYPE_ACK) {
        strncpy(context->user.password, newPassword, sizeof(context->user.password) - 1);
        logInfo("Change password successful");
        return 0;
    }
    
    logError("Change password failed");
    return -1;
}

// 删除用户
int userDelete(ClientContext *context, const char *username) {
    cJSON *root = cJSON_CreateObject();
    cJSON_AddStringToObject(root, "username", username);
    cJSON_AddStringToObject(root, "operator", context->user.username);
    
    char *jsonStr = cJSON_PrintUnformatted(root);
    int ret = sendPacket(context->sockfd, DATA_TYPE_USER_DELETE, jsonStr);
    
    cJSON_free(jsonStr);
    cJSON_Delete(root);
    
    if (ret < 0) {
        logError("Failed to send delete user request");
        return -1;
    }
    
    // 等待响应
    char responseBuffer[MAX_BUFFER_SIZE];
    unsigned char responseType;
    waitForResponse(responseBuffer, MAX_BUFFER_SIZE, &responseType);
    
    if (responseType == DATA_TYPE_ACK) {
        logInfo("Delete user successful");
        return 0;
    }
    
    logError("Delete user failed");
    return -1;
}

// 查询用户
int userQuery(ClientContext *context, const char *username) {
    cJSON *root = cJSON_CreateObject();
    if (username) {
        cJSON_AddStringToObject(root, "username", username);
    }
    cJSON_AddStringToObject(root, "operator", context->user.username);
    
    char *jsonStr = cJSON_PrintUnformatted(root);
    int ret = sendPacket(context->sockfd, DATA_TYPE_USER_QUERY, jsonStr);
    
    cJSON_free(jsonStr);
    cJSON_Delete(root);
    
    if (ret < 0) {
        logError("Failed to send query user request");
        return -1;
    }
    
    // 等待响应
    char responseBuffer[MAX_BUFFER_SIZE];
    unsigned char responseType;
    waitForResponse(responseBuffer, MAX_BUFFER_SIZE, &responseType);
    
    // 打印用户信息
    printf("\n--- User Query Results ---");
    printf("%s\n", responseBuffer);
    printf("------------------------\n");
    
    return 0;
}

// 显示登录菜单
void showLoginMenu() {
    printf("\n==================================\n");
    printf("        光伏生产监测系统客户端        \n");
    printf("==================================\n");
    printf("1. 用户登录\n");
    printf("2. 用户注册（仅维护工程师可注册）\n");
    printf("0. 退出系统\n");
    printf("==================================\n");
    printf("请选择操作: ");
}

// 显示主菜单
void showMainMenu(const char *role) {
    printf("\n==================================\n");
    printf("        光伏生产监测系统客户端        \n");
    printf("角色: %s\n", role);
    printf("==================================\n");
    printf("用户管理:\n");
    printf("1. 修改密码\n");
    
    if (strcmp(role, "maintenance_engineer") == 0) {
        printf("2. 注册新用户\n");
        printf("3. 删除用户\n");
        printf("4. 查看所有用户\n");
    }
    
    printf("\n数据管理:\n");
    printf("%d. 查询检测记录\n", strcmp(role, "maintenance_engineer") == 0 ? 5 : 2);
    printf("%d. 删除检测记录\n", strcmp(role, "maintenance_engineer") == 0 ? 6 : 3);
    printf("%d. 申请抽查数据\n", strcmp(role, "maintenance_engineer") == 0 ? 7 : 4);
    printf("%d. 上传错误数据编号\n", strcmp(role, "maintenance_engineer") == 0 ? 8 : 5);
    printf("%d. 查询本地数据文件\n", strcmp(role, "maintenance_engineer") == 0 ? 9 : 6);
    
    printf("\n0. 退出登录\n");
    printf("==================================\n");
    printf("请选择操作: ");
}